import React, { useState, useEffect } from 'react'
import { Form, Input, Button, Card, Row, Col } from 'antd'
import { UserOutlined, LockOutlined, SafetyOutlined } from '@ant-design/icons'
import { useDispatch, useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { RootState } from '@/store'
import { login } from '@/store/slices/authSlice'
import { LoginData } from '@/types/auth'
import authService from '@/services/auth'
import { checkTokenInCache, debugAuthState } from '@/utils/auth'
import styles from './index.module.css'

const LoginPage: React.FC = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const { loading } = useSelector((state: RootState) => state.auth)
  const [form] = Form.useForm()
  const [captchaImage, setCaptchaImage] = useState('')
  const [requestId, setRequestId] = useState('')

  // 获取验证码
  const fetchCaptcha = async () => {
    try {
      // 使用AuthService获取验证码
      const response = await authService.getCaptcha()
      if (response && response.data) {
        const { requestId, captchaImage } = response.data
        setCaptchaImage(captchaImage)
        setRequestId(requestId)
      }
    } catch (error) {
      // 获取验证码请求失败
    }
  }

  // 组件挂载时获取验证码
  useEffect(() => {
    fetchCaptcha()
  }, [])

  const handleSubmit = async (values: LoginData) => {
    try {
      // 添加验证码和requestId
      const loginData = {
        ...values,
        requestId: requestId
      }
      // 登录是否成功   
      const result = await dispatch(login(loginData as any) as any).unwrap()
      console.log("登录结果：",result)      
      if (result) {
        // 验证 token 是否正确存储到缓存
        setTimeout(() => {
          debugAuthState()
          checkTokenInCache()
        }, 200)

        navigate('/', { replace: true })
      }
    } catch (error) {
      console.log("登录失败：",error)
      // 刷新验证码
      fetchCaptcha()
    }
  }

  return (
    <div className={styles.loginContainer}>
      <div className={styles.loginBox}>
        <Card className={styles.loginCard}>
          <div className={styles.loginHeader}>
            <h1>CoreManager</h1>
            <p>后台管理系统</p>
          </div>
          
          <Form
            form={form}
            name="login"
            onFinish={handleSubmit}
            autoComplete="off"
            size="large"
          >
            <Form.Item
              name="userName"
              rules={[
                { required: true, message: '请输入用户名!' },
                { min: 3, message: '用户名至少3个字符!' }
              ]}
            >
              <Input 
                prefix={<UserOutlined />} 
                placeholder="用户名" 
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入密码!' },
                { min: 6, message: '密码至少6个字符!' }
              ]}
            >
              <Input.Password 
                prefix={<LockOutlined />} 
                placeholder="密码" 
              />
            </Form.Item>

            <Form.Item
              name="captchaCode"
              rules={[
                { required: true, message: '请输入验证码!' }
              ]}
            >
              <Row gutter={8}>
                <Col span={16}>
                  <Input 
                    prefix={<SafetyOutlined />} 
                    placeholder="验证码" 
                  />
                </Col>
                <Col span={8}>
                  <div 
                    onClick={fetchCaptcha}
                    style={{ 
                      cursor: 'pointer', 
                      height: '40px',
                      overflow: 'hidden',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      border: '1px solid #d9d9d9',
                      borderRadius: '2px',
                      backgroundColor: '#f5f5f5'
                    }}
                  >
                    {captchaImage ? (
                      <img 
                        src={`data:image/png;base64,${captchaImage}`} 
                        alt="验证码" 
                        style={{ 
                          maxWidth: '100%', 
                          maxHeight: '100%',
                          objectFit: 'fill'
                        }}
                        onLoad={() => {}}
                        onError={() => {
                          // 验证码图片加载失败
                        }}
                      />
                    ) : (
                      <span style={{ color: '#999', fontSize: '12px' }}>
                        {requestId ? '点击刷新' : '加载中...'}
                      </span>
                    )}
                  </div>
                </Col>
              </Row>
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={loading}
                block
              >
                登录
              </Button>
            </Form.Item>
          </Form>

          <div className={styles.loginFooter}>
            <p>后台管理系统</p>
          </div>
        </Card>
      </div>
    </div>
  )
}

export default LoginPage